var sqlCon = require('../mysql/index');
var Mapper = require('../mysql/seque');

async function selectAllRooms() {
  return await Mapper.Room.findAll({
    order: [
      ['createdAt', 'DESC']
    ]
  });
};

async function insertRoom(roomname, userid, blackUser, whiteUser, chessSize, letNum, blackName, whiteName, username) {
  return await Mapper.Room.create({
    roomname: roomname,
    roomOwner: userid,
    roomOwnerName: username,
    blackUser: blackUser,
    whiteUser: whiteUser,
    chessSize: chessSize,
    letNum: letNum,
    blackName: blackName,
    whiteName: whiteName
  });
};

async function updateWhite(roomid, userid, username, whiteStatus) {
  return await Mapper.Room.update({
    whiteStatus: whiteStatus, // 已就绪
    whiteUser: userid,
    whiteName: username
  }, {
    where: {
      id: roomid
    }
  });
};

async function updateBlack(roomid, userid, username, blackStatus) {
  return await Mapper.Room.update({
    blackStatus: blackStatus, // 已就绪
    blackUser: userid,
    blackName: username
  }, {
    where: {
      id: roomid
    }
  });
};

async function insertUserRoom(roomid, userid) {
  var sql = `UPDATE t_users SET roomid = '${roomid}' WHERE id = '${userid}'`;
  var result = await sqlCon.query(sql);
  return result;
}

async function insertRoomColor(roomid, userid, username, color) {
  
  var sql = `UPDATE t_room SET colorHuser = '${userid}', colorHusername = '${username}' WHERE id = '${roomid}'`;
  if (color == 'B') {
    sql = `UPDATE t_room SET colorBuser = '${userid}', colorBusername = '${username}' WHERE id = '${roomid}'`;
  }
  var result = await sqlCon.query(sql);
  return result;
};

async function selectRoomById(roomid) {
  var result = await Mapper.Room.findOne({
    where: {
      id: roomid
    }
  });
  return result.toJSON();
}

async function updateRoomStatus(roomid, status) {
  return await Mapper.Room.update({
    roomStatus: status
  }, {
    where: {
      id: roomid
    }
  });
}

module.exports = {
  selectAllRooms,
  insertUserRoom,
  insertRoomColor,
  selectRoomById,
  updateRoomStatus,
  insertRoom,
  updateWhite,
  updateBlack
};